<?php

namespace App\Http\Middleware;

use Closure;

class AccAllowOrg
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $allowOrigin =  explode(',' ,\Config::get('app.allow_origin'));

        $requestHeader = $request->header();
        if(isset($requestHeader['origin'])) {
            $origin = $requestHeader['origin'];
            $originUrl = parse_url($origin[0]);
            $url = $originUrl['host'];
            if(isset($originUrl['port'])){
                $url .= ':' . $originUrl['port'];
            }
            if (in_array($url, $allowOrigin)) {
                header('Access-Control-Allow-Origin:http://' . $url);
            }
//        header('Access-Control-Allow-Origin:http://'.$host);
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
        }
        return $next($request);
    }
}
